package com.xixibaby.message.channel.dingding;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.xixibaby.core.Prototypes;
import com.xixibaby.core.message.BaseChannelHandler;
import com.xixibaby.core.message.ChannelHandler;
import org.springframework.beans.factory.annotation.Value;

import java.util.Map;

/**
 * @author tooomj
 */
@Prototypes(key = ChannelHandler.class,value = 2)
public class DingdingHandler extends BaseChannelHandler<DDMessage> {

    private static final String URL = "https://oapi.dingtalk.com/robot/send?access_token={}";

    @Value("${spring.dingding.token}")
    private String token;

    @Override
    public DDMessage convertToParam(Map<String, Object> context) {
        return Convert.convert(DDMessage.class, context);
    }

    @Override
    protected boolean handler(String target, DDMessage param) {
        DDMessage.At at = new DDMessage.At();
        at.setAtMobiles(new String[]{target});
        param.setAt(at);
        String s = JSONObject.toJSONString(param);
        String post = HttpUtil.post(StrUtil.format(URL, token), s);
        JSONObject parse = JSONObject.parseObject(post);
        return parse.getInteger("errcode") == 0;
    }

}
